<template>
    <div class="container">
        <div class="header">
            <span class="Data_font">场景片段</span> 
            <div class="header-right">
                <el-dropdown>
                    <span class="user_icon">
                        <img src="../../../../assets/images/user-icon.png">
                    </span>
                    <el-dropdown-menu @click.native='handleUserSetting("loginout")' style="fontSize:12px;padding: 10px 20px;cursor:pointer">
                        退出登录
                    </el-dropdown-menu>
                </el-dropdown>
                <alarm-icon></alarm-icon>
            </div>
        </div>
        <div class="main">
            <div class="main-header">
                <div class="btn_setion">
                    <el-button @click="batchArchiveOperation" :disabled="storageTypeBtn" type="primary" plain>修改存储类别</el-button>
                    <el-button @click="handleMoreBtn('recovery')" :disabled="recoveryBtn" type="info" plain>恢复</el-button>
                    <el-button type="info" plain :disabled="downloadBtn" @click="handleMoreBtn('download')">下载</el-button>
                    <el-button type="info" plain @click="batchDeleteSceneData">删除</el-button>
                </div>
                <div class="ipt_section">
                    <search
                    :options = 'searchBoxOptions'
                    @change = "searchChange"
                    >
                    </search>
                    <div class="setting-icon el-icon-refresh-left" @click="getTableData"></div>
                </div>
            </div>
            <!-- 表格区域 -->
            <el-table
                tooltip-effect="dark"
                :header-cell-style="{
                    color: '#131416', fontsize: '0.875rem',
                    fontWeight: 'Bold', fontFamily:'Microsoft YaHei, Microsoft YaHei-Bold',
                    backgroundColor:'#F8F8F8',height:'2.5rem'}"
                :row-style="{height:'3.375rem'}"
                :cell-style="{}"
                style="margin-top:2.5rem; margin-bottom: 1.875rem;border: 1px solid #e6e6e6; border-radius: 2px;"
                border
                :data="tableList"
                @selection-change="handleSelectionChange"
                v-loading="loading"
                >
                <el-table-column
                    type="selection"
                    width="50">
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="数据包名称">
                     <template slot-scope="scope"> 
                        <span 
                            :style="{ color: scope.row.name ? '#2D58C3' : '#2D58C3' ,cursor:'pointer' }"
                            @click="handlePreview(scope.row)"
                        >            
                            {{ scope.row.name }}          
                        </span>        
                    </template> 
                </el-table-column>
                <el-table-column
                    prop="size"
                    label="数据大小">
                    <template slot-scope="scope">          
                        {{ formatBytes(scope.row.size, 0) }}              
                    </template> 
                </el-table-column>
                <el-table-column
                    prop="car_id"
                    label="采集车辆"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="data_status"
                    label="数据状态"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="scope.row.data_status === 0" >{{'待审核'}}</span>
                        <span v-if="scope.row.data_status === 1" >{{'标注中'}}</span>
                        <span v-if="scope.row.data_status === 2" >{{'标注完成'}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="data_type"
                    label="数据类型"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="scope.row.data_type === 0" >{{'融合数据'}}</span>
                        <span v-if="scope.row.data_type === 1" >{{'CAN/GPS'}}</span>
                        <span v-if="scope.row.data_type === 2" >{{'相机'}}</span>
                        <span v-if="scope.row.data_type === 3" >{{'毫米波雷达'}}</span>
                        <span v-if="scope.row.data_type === 4" >{{'激光雷达'}}</span>
                        <span v-if="scope.row.data_type === 5" >{{'超声波'}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="storage_type"
                    label="存储类型"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="scope.row.storage_type === 0" >{{'标准存储'}}</span>
                        <span v-if="scope.row.storage_type === 1" >{{'低频存储'}}</span>
                        <span v-if="scope.row.storage_type === 2" >{{'归档存储'}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="restoration_status"
                    label="恢复状态"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="scope.row.restoration_status === 0" >{{'--'}}</span>
                        <span v-if="scope.row.restoration_status === 1" >{{'未恢复'}}</span>
                        <span v-if="scope.row.restoration_status === 2" >{{'恢复中'}}</span>
                        <span v-if="scope.row.restoration_status === 3" >{{'已恢复'}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="collect_time"
                    label="提取时间"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span>{{scope.row.collect_time | dataFormat('YYYY/MM/DD')}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="tag"
                    label="标签"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="scope.row.tag" class="tagStyle">
                            <el-tag type="info" v-for="(itm, index) in scope.row.tag" :key="index" effect="plain" size="small">{{itm}}</el-tag>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                >
                    <template slot-scope="scope">
                        <el-button
                            @click="handleSingleArchive(scope.row)"
                            v-if="scope.row.singleStorageType"
                            type="text"
                            size="small" class="buttonLine">
                            修改存储类型
                        </el-button>
                        <el-button
                            @click="handleSingleRecovery(scope.row)"
                            v-if="scope.row.singleRecovery"
                            type="text"
                            size="small" class="buttonLine">
                            恢复
                        </el-button>
                        <el-button
                            @click="handleDownload(scope.row)"
                            v-if="scope.row.isDownloadable"
                            type="text"
                            size="small" class="buttonLine">
                            下载
                        </el-button>
                        <el-button
                            @click="handleDelete(scope.row)"
                            type="text"
                            size="small" class="buttonLine">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 50, 100, 150, 200]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount"
                v-if="totalCount > 0"
                >
            </el-pagination>
        </div>
        <!-- 归档 -->
        <el-dialog
            title="修改存储类别"
            :visible.sync="archiveOperationDialogVisible"
            width="25%"
            :showClose="false"
            :before-close="modifyCategoryCancel"
            >
            <div class="storage_section">
                <span class="store">存储类别</span>
                <el-radio-group v-model="storeOptions">
                    <el-radio :label = 0 :disabled="standardRadio">标准存储</el-radio>
                    <el-radio :label = 1 :disabled="lowerRadio">低频访问存储</el-radio>
                    <el-radio :label = 2 :disabled="fileRadio">归档存储</el-radio>
                </el-radio-group>
                <p v-if="storeOptions === 0">适用于有大量热点文件或小文件，且需要频繁访问（平均一个月多次）并快速获取数据的业务场景。</p>
                <p v-if="storeOptions === 1">适用于不频繁访问（平均一年少于12次），但快速获取数据的业务场景。</p>
                <p v-if="storeOptions === 2">适用于很少访问（平均一年一次）且对数据获取速率要求不高的业务场景。</p>
            </div>
            <span slot="footer" class="store_footer">
                <el-button size="small" plain type="primary" @click="modifyCategoryConfirm">确 定</el-button>
                <el-button size="small" plain type="info" @click="modifyCategoryCancel">取 消</el-button>
            </span>
        </el-dialog>
        
        <!-- 恢复操作 -->
        <el-dialog
            title="恢复"
            :visible.sync="retrievesOperationDialogVisible"
            width="25%"
            :showClose="false"
            :before-close="recoveryCancel"
            >
            <div class="validity_section">
                <span>有效期</span>
                <span style="margin: 0px 10px 0 64px;">
                    <el-input-number v-model="dayNum" :min="1" :max="30"></el-input-number>
                </span>
                <span class="validity_day">天</span>
                <div style="paddingLeft: 100px;paddingTop: 10px">有效期限制为1~30天</div> 
            </div>
            <div class="speed_section">
                <span class="rate">速率</span>
                <el-radio-group v-model="speedOptions">
                    <el-radio label="EXPEDITED">加急</el-radio>
                    <el-radio label="STANDARD">标准</el-radio>
                </el-radio-group>
                <p v-if="speedOptions === 'EXPEDITED'">可在3~5分钟内恢复以上对象。</p>
                <p v-if="speedOptions === 'STANDARD'">可在3~5小时内恢复以上对象。</p>
            </div>
            <span slot="footer" class="recovery_footer">
                <el-button size="small" plain type="primary" @click="recoveryConfirm">确 定</el-button>
                <el-button size="small" plain type="info" @click="recoveryCancel">取 消</el-button>
            </span>
        </el-dialog>

        <!-- 单行下载操作 -->
        <el-dialog
            :visible.sync="downLoadDialogVisible"
            width="40%"
            center
            :before-close="handleFileDownClose"
            >
            <el-table :data="fileData">
                <el-table-column property="fileName" label="文件名" width="400"></el-table-column>
                <el-table-column label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button
                            @click="handleFileDownload(scope.row)"
                            type="text"
                            size="small">
                            下载
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import Search from '@/components/searchBox/searchBox.vue'
import alarmIcon from '../../../../components/alarmIconComponent/alarmIconComponent.vue'
import { searchBoxOptions } from '@/components/data.js'
export default {
    components: {
        Search,
        alarmIcon,
    },
    data() {
        return {
            // 搜索框参数
            searchBoxOptions: [],
            // 默认每页数据量
            pageSize: 10,
            // 当前页码
            currentPage: 1,
            // 默认数据总数,表格的分页
			totalCount: 0,
            tableList: [],
            multipleSelection: [],
            recoveryBtn: false,
            storageTypeBtn: false,
            downloadBtn: false,
            archiveOperationDialogVisible: false,
            retrievesOperationDialogVisible: false,
            scenarioOperationDialogVisible: false,
            downLoadDialogVisible: false,
            dayNum: 1,
            speedOptions: 'EXPEDITED',
            storeOptions: 0,
            pkRecoveryStore: '',
            pkArchivingStore:'',
            searchContent: '',
            fileData: [],
            standardRadio: false,
            lowerRadio: false,
            fileRadio: false,
            loading: false,
        }
    },
     mounted(){
      this.getTableData(this.id);
      let options = JSON.parse(JSON.stringify(searchBoxOptions));
      options.pop();
      this.searchBoxOptions=options;
    },
    methods: {
        // 获取表格列表
        getTableData() {
            this.loading = true;
            this.$url.get(`data/scene/list?page=${this.currentPage}&page_size=${this.pageSize}`)
            .then( res=> {
                if (res.status === 200) {
                    this.tableList = res.data.data.data_list;
                    this.totalCount = res.data.data.count;
                    this.setTableDetail();
                    this.setTableStatus();
                    this.searchBoxOptions.forEach((g,index) => {
                        let obj = {}
                        g.options = g.options.reduce((newArr,m) => {
                            obj[m.label] ? '' : (obj[m.label] = true && newArr.push(m))
                            return newArr
                        }, [])
                        return g.options
                    })
                }
                this.loading = false
            })
            .catch(err=>{
                this.loading = false
            })
        },       
        setTableDetail() {
            this.tableList.forEach(i=> {
                this.searchBoxOptions.forEach(k => {
                    if (k.id === 'storage_type') {
                        if (i.storage_type === 0) {
                            k.options.push({label: '标准存储'})
                        } else if (i.storage_type === 1) {
                            k.options.push({label: '低频存储'})
                        } else if (i.storage_type === 2) {
                            k.options.push({label: '归档存储'})
                        }
                    } else if (k.id === 'data_type') {
                        if (i.data_type === 0) {
                            k.options.push({label: '融合数据'})
                        } else if (i.data_type === 1) {
                            k.options.push({label: 'CAN/GPS'})
                        } else if (i.data_type === 2) {
                            k.options.push({label: '相机'})
                        } else if (i.data_type === 3) {
                            k.options.push({label: '毫米波雷达'})
                        } else if (i.data_type === 4) {
                            k.options.push({label: '激光雷达'})
                        } else if (i.data_type === 5) {
                            k.options.push({label: '超声波'})
                        } 
                    }
                })
            })
        },
        setTableStatus() {
            if(this.tableList){
              this.tableList.forEach(item => {
                if (item.tag) {
                    item.tag = item.tag.split('|')
                }
                let isDownloadable  = false;
                item[isDownloadable] = false;
                if (item.storage_type === 2 && item.restoration_status === 3 || item.storage_type !== 2) {
                    item.isDownloadable = true;
                } else {
                    item.isDownloadable = false;
                }

                let singleRecovery = false;
                item[singleRecovery] = false;
                if (item.storage_type === 2 && item.restoration_status === 1 ||  item.restoration_status === 3) {
                    item.singleRecovery = true;
                } else {
                    item.singleRecovery = false;
                }

                let singleStorageType = false;
                item[singleStorageType] = false;
                if (item.storage_type !== 2 || item.storage_type === 2 && item.restoration_status === 3) {
                    item.singleStorageType = true;
                } else {
                    item.singleStorageType = false;
                }
            })  
          }
        },
        // 搜索事件
        searchChange(content) {
            let params = {
                page: this.currentPage,
                pageSize: this.pageSize
            }
            content.forEach(i => {
                if (i.value === '标准存储') {
                    i.value = 0;
                } else if (i.value === '低频存储') {
                    i.value = 1;
                } else if (i.value === '归档存储') {
                    i.value = 2;
                } 

                if(i.value === '融合数据') {
                    i.value = 0;
                } else if (i.value === 'CAN/GPS') {
                    i.value = 1;
                } else if (i.value === '相机') {
                    i.value = 2;
                } else if (i.value === '毫米波雷达') {
                    i.value = 3;
                } else if (i.value === '激光雷达') {
                    i.value = 4;
                } else if (i.value === '超声波') {
                    i.value = 5;
                }
            })
            content.forEach(item => {
                params[item.id] = item.value
            })
            this.$url.get('data/scene/list', {params})
            .then( res => {
                if (res.status === 200) {          
                    this.tableList = res.data.data.data_list;
                    this.totalCount = res.data.data.count
                    this.setTableStatus();
                    if(this.tableList){
                           this.tableList.forEach(item => {
                        if (item.tag) {
                            item.tag = item.tag.split('|')
                        }
                    })                
                }
                    }       
            })
        },
        formatBytes(a, b) { 
            if (a == 0) return '0 B'; 
            var c = 1024, d = b, e = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], f = Math.floor(Math.log(a) / Math.log(c)); 
            return parseFloat((a / Math.pow(c, f)).toFixed(d)) + ' ' + e[f];
        },
        // 批量删除操作
        batchDeleteSceneData() {
            if (this.multipleSelection.length === 0) return this.$message.error('请至少选择一项');
                this.$confirm('确定删除这些数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let ids = [];
                this.multipleSelection.forEach(element => {
                    this.tableList.forEach((item,index) => {
                        if (element.id === item.id) {
                            ids.push(item.id)
                        }
                    })
                })
                let formData = new FormData()
                formData.append('ids', ids)
                this.$url.delete('data/scene/list', {data: formData})
                .then (res => {
                    if (res.status === 204) {
                        this.$message.success('批量删除成功')
                        this.getTableData()
                    }
                })
                .catch(err => {
                    if (!err.response.data.code) this.$message.error('批量删除失败')
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        // 更多按钮点击事件
        handleMoreBtn(command) {
            if (this.multipleSelection.length === 0) return this.$message.error('请至少选择一项');
            if (command === 'recovery') {
                this.retrievesOperationDialogVisible = true;
            } 
            if (command == 'download') {
                this.handleDownload(this.multipleSelection[0])
            }
        },
        // 表格选中与否
        handleSelectionChange(val) {
            this.multipleSelection = val;
            this.recoveryBtn = false;
            this.storageTypeBtn = false;
            this.downloadBtn =  false;
            let downCount = 0;
            this.multipleSelection.forEach(item => {
                if (!item.singleStorageType) {
                    this.storageTypeBtn = true;
                }
                if (!item.singleRecovery) {
                    this.recoveryBtn = true;
                }
                if (!item.isDownloadable) {
                    this.downloadBtn = true;
                } else {
                    downCount++;
                }
            })
            if (downCount > 1) this.downloadBtn = true;
        },
        // 单行预览事件
        handlePreview(pk) {
            this.$url.get('data/scene/'+ pk.id)
            .then(res=>{
                if (res.data.data) {
                    this.$router.push({
                        path:'/SceneSnippet',
                        query: res.data
                    })
                }
            })
            .catch(res=>{
                if(!res.response.data.code) this.$message.error('请求错误')
            })
        },
        // 单行下载事件
        handleDownload(pk) {
            this.$url.get('data/scene/download/'+ pk.id ) 
            .then(res=>{
		   	   	if (res.status === 200) {
                    let urls = res.data.data.data;
                    Object.keys(urls).forEach(index => {
                        window.open(urls[index],index);
                    });
                    this.$message.success('下载成功')
                } else {
		   	   	    this.$message.error('下载失败')
                }
		   	})
        },
        // 关闭文件下载弹框事件
        handleFileDownClose() {
            this.downLoadDialogVisible = false;
            this.fileData = [];
        },
        // 单行删除事件
        handleDelete(pk) {
            this.$confirm('确定删除此数据？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$url.delete('data/scene/'+ pk.id)
                .then(res => {
                    if (res.status === 204) {
                        this.$message.success('删除数据成功')
                        this.getTableData()
                    } else {
                        this.$message.error('删除数据失败')
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        // 单行归档点击事件
        handleSingleArchive(pk) {
            if (pk.storage_type == 0) {
                this.standardRadio = true;
                this.lowerRadio = false;
                this.fileRadio = false;
                this.storeOptions = 1;
            }
            else if (pk.storage_type == 1) {
                this.standardRadio = false;
                this.lowerRadio = true;
                this.fileRadio = false;
                this.storeOptions = 0;
            }
            else {
                if (pk.restoration_status == 3) {
                    this.standardRadio = false;
                    this.lowerRadio = false;
                    this.fileRadio = true;
                    this.storeOptions = 0;
                }
            }
            this.archiveOperationDialogVisible = true;
            this.pkArchivingStore = pk.id;
        },
        // 批量修改存储类型点击事件
        batchArchiveOperation(){
            if (this.multipleSelection.length === 0) return this.$message.error('请至少选择一项');
                this.standardRadio = false;
                this.lowerRadio = false;
                this.fileRadio = false;
                this.multipleSelection.forEach(item=>{
                    if (item.storage_type == 0) {
                        this.standardRadio = true;
                    }
                    else if (item.storage_type == 1) {
                        this.lowerRadio = true;
                    }
                    else {
                        if (item.restoration_status == 3) {
                            this.fileRadio = true;
                        }
                    }
                })
            if (this.standardRadio == false) {
                this.storeOptions = 0;
            } else if (this.lowerRadio == false) {
                this.storeOptions = 1;
            } else if (this.fileRadio == false) {
                this.storeOptions = 2;
            } else this.storeOptions = false;
            this.archiveOperationDialogVisible = true;
        },
        // 修改存储类型确认事件
        modifyCategoryConfirm() {
            if (this.storeOptions !== false) {
                let ids = []
                if (this.pkArchivingStore) {               
                    ids.push(this.pkArchivingStore);
                } else {
                    this.multipleSelection.forEach(element => {
                        this.tableList.forEach((item,index) => {
                            if (element.id === item.id) {
                                ids.push(item.id)
                            }
                        })
                    })
                }
                this.$url.post('data/scene/storageclass', {
                    'ids': ids,
                    'storage_class': this.storeOptions
                })
                .then(res=>{
                    if (res.status === 200) {
                        this.$message.success('修改成功')
                        this.getTableData()
                    } else {
                        this.$message.error('修改失败')
                    }
                    this.pkArchivingStore = '';
                    this.storeOptions = 0;
                    this.archiveOperationDialogVisible = false;
                })
            }
        },
        // 归档取消事件
        modifyCategoryCancel() {
            this.storeOptions = 0;
            this.pkArchivingStore = '';
            this.archiveOperationDialogVisible = false;
        },
        // 单行恢复点击事件
        handleSingleRecovery(pk) {
            this.retrievesOperationDialogVisible = true;
            this.pkRecoveryStore = pk.id;
        },
        // 批量恢复或单行恢复确认事件
        recoveryConfirm() {
            let ids = [];
            if (this.pkRecoveryStore) {  
                ids.push(this.pkRecoveryStore)
            } else {
                this.multipleSelection.forEach(element => {
                    this.tableList.forEach((item,index) => {
                        if (element.id === item.id) {
                            ids.push(item.id)
                        }
                    })
                })
            }
            this.$url.post('data/scene/restore', {
                'ids': ids,
                'days_num': this.dayNum,
                'rate': this.speedOptions
            })
            .then(res => {
                if (res.status === 200) {
                    this.$message.success('恢复成功')
                    this.getTableData()
                } else {
                    this.$message.error('恢复失败')
                }
            }) 
            this.pkRecoveryStore = '';
            this.speedOptions = 'EXPEDITED';
            this.dayNum = 1;
            this.retrievesOperationDialogVisible = false;
        },
        // 恢复取消事件
        recoveryCancel() {
            this.pkRecoveryStore = '';
            this.speedOptions = 'EXPEDITED';
            this.dayNum = 1;
            this.retrievesOperationDialogVisible = false;
        },
        
        handleSizeChange(val) {
            this.pageSize = val;
            this.getTableData()
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.getTableData()
        },
        // 退出登录
        handleUserSetting(command) {
          if (command === 'loginout') {
            this.$url.post('logout')
                .then(res => {
                    if (res.status === 200) {
                        this.$message.success('退出成功')
                        this.$router.push({ path:'/Login'})
                        this.$stor.del('X-CSRFToken')
                    }
                })
            }
        },
    }
}
</script>

<style lang="less" src="../../../../assets/css/anonymizeDataPageStyle.less">
</style>